#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

#include "CImg/CImg.h"

using namespace std;
using namespace cimg_library;

void print_usage() {
	cout << "usage: img2arr <src img(bmp)> <out path> [-c]" << endl;
	cout << "  -c: NOT IMPLEMENTED! compress alpha byte, make RGBA (4 char) to RGB (3 char)." << endl;
}

static ofstream fout;
static bool flag_compress_alpha = false;

vector<int32_t> img2vec(const char *imgin) {
	CImg<unsigned char> img(imgin);
	vector<int32_t> buf;

	unsigned w = static_cast<unsigned>(img.width()), h = static_cast<unsigned>(img.height()), wh = w * h;
	for(unsigned x = 0; x < w; x++) {
		for (unsigned y = 0; y < h; y++) {
			unsigned t = img(x, y, 0, 0, wh) + img(x, y, 0, 1, wh) + img(x, y, 0, 2, wh);
			buf.push_back(static_cast<int32_t>(t));
		}
	}
	return buf;
}

void vec2bin(const vector<int32_t> &buf) {
	fout.write(reinterpret_cast<const char*>(buf.data()), buf.size()*4);
	fout.flush();
}

int main(int argc, char* argv[]) {
	if(argc < 3 || argc > 4) {
		print_usage();
		return -1;
	}
	if(argc == 4) {
		if(!strcmp(argv[3], "-c"))
			flag_compress_alpha = true;
		else {
			print_usage();
			return -1;
		}
	}

	fout.open(argv[2]);
	vec2bin(img2vec(argv[1]));

	return 0;
}
